package generator;

import org.eclipse.uml2.uml.Element;
import java.util.Properties;

public abstract class BaseTemplateClass {

	protected Element element;
	protected Properties properties;
	protected StringBuilder returningString = new StringBuilder();

	public BaseTemplateClass(Properties properties) {
		this.properties = properties;
	}

	public boolean isProcessable() {
		return true;
	}

	public void createFile() {
	}

	public void setElement(Element ele) {
		this.element = ele;
		returningString = new StringBuilder();
	}

	public String returning() {
		return _returning();
	}

	protected abstract String _returning();

	/**
	 * Return the String with the first letter uppercase. Useful for class name.
	 */
	public String firstUpper(String s) {
		if (s.length() > 0) {
			s = Character.toUpperCase(s.charAt(0)) + s.substring(1);
		}
		return s;
	}

	/**
	 * Return the String with the first letter lowercase. Useful for attribute
	 * name.
	 */
	public String firstLower(String s) {
		if (s.length() > 0) {
			s = Character.toLowerCase(s.charAt(0)) + s.substring(1);
		}
		return s;
	}

	/**
	 * Transform a String with notation aa.bb.cc to aa/bb/cc
	 * Usefull for package translating.
	 */
	public String toPath(String packageName) {
		return packageName.trim().replaceAll("\\.", "/");
	}

	/**
	 * Retorna el nombre del elemento, o una cadena vacía si el elemento no es NamedElement.
	 *
	 * @param elt
	 * @return
	 */
	public String getName(Element elt) {
		if (elt	instanceof org.eclipse.uml2.uml.NamedElement) {
			return ((org.eclipse.uml2.uml.NamedElement)elt).getName();
		}
		return "";
	}

	/**
	 * Verify if an Element have a stereotype. Use keyword and profil to find
	 * stereotype. Multiple stereotype are allow.
	 *
	 * @param elt 
	 * 		Element used.
	 * @param stereotype
	 * 		Stereotype to search.
	 * @return true if found. false else.
	 */
	public boolean hasStereotype(Element elt, String stereotype) {
		if (elt instanceof org.eclipse.uml2.uml.Class) {
			// search with real stereotype
			org.eclipse.uml2.uml.Stereotype stereotypeFound = elt.getApplicableStereotype(stereotype);

			for (org.eclipse.uml2.uml.Stereotype s : elt.getApplicableStereotypes()) {
				if (s.getName().equals(stereotype)) {
					stereotypeFound = s;
				}
			}
			if (stereotypeFound == null) {
				// search with keywords
				if (elt.hasKeyword(stereotype)) {
					return true;
				}
			} else {
				return true;
			}
		}
		return false;
	}
	
	public String templateNameToClassName(String templateName) {
		StringBuilder sb = new StringBuilder();
		boolean begin = true;
		for (int i = 0; i < templateName.length(); i++) {
			char c = templateName.charAt(i);
			if (c == '.' || c == '_') {
				begin = true;
			} else {
				if (begin) {
					c = Character.toUpperCase(c);
					begin = false;
				}
				sb.append(c);
			}
		}
		return sb.toString();
	}

	public boolean isMethod(String name) {
		return (name != null && name.trim().length() > 0 && name.indexOf('(') != -1);
	}	
	
}